import superagent from "superagent"
import cheerio from "cheerio"
import fs from "fs"
import path from "path"

interface name4 {
  title: string,
  count:number
}
interface result {
  tiem: number,
  data:name4[]
}
interface Content {
  [propName:number]:name4[]
  
}
class Crowller {
  private url: string = "http://127.0.0.1:5500/index.html"

  getJsonInfo(html:string) {
    const $ = cheerio.load(html)
    const courseitem = $('.course-item')
    const coursInfos: name4[] = []
    courseitem.map((index, element) => {
      //找到标题
      const coursedesc = $(element).find('.course-desc')
      const title = coursedesc.eq(0).text() 
      //找到当前学习人数
      const student = $(element).find('.course-textitem')
      const number1 = student.eq(0).text()
      const count = parseInt(number1)
      coursInfos.push({
        title,
        count
      })
    })
    const result:result = {
        tiem: (new Date()).getTime(),
        data:coursInfos
      }
    this.generateJsonContent(result)
  }
  generateJsonContent(result: result) {
    //读取当前路径下的../data/course.json文件
    const filePath = path.resolve(__dirname, "../data/course.json")
    let fileContent:Content = {}
    if (fs.existsSync(filePath)) {
      //读取文件类容 存放在当前文件
      fileContent = JSON.parse(fs.readFileSync(filePath, "utf8"))
    }
    //如果没有这个文件那我就拿到这个对象来添加属性 然后在把这个对象添加到filePath路径下的文件中去
    fileContent[result.tiem] = result.data
    fs.writeFileSync(filePath, JSON.stringify(fileContent))
    
  }
  async gethtml() {
    const name2 = await superagent.get(this.url)
    this.getJsonInfo(name2.text)
  }

  constructor() {
    this.gethtml()
  }
}
const name1 = new Crowller()
